// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'getImages') {
    // 确保消息来自我们的content script
    if (sender.tab) {
      sendResponse({ success: true });
    }
  }
  return true; // 保持消息通道开启
});

// 监听标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete') {
    // 当页面加载完成时通知content script
    chrome.tabs.sendMessage(tabId, { type: 'pageLoaded' })
      .catch(error => {
        console.log('Tab communication error:', error);
      });
  }
});

// 处理下载任务
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'download') {
    chrome.downloads.download({
      url: request.url,
      filename: request.filename || null,
      saveAs: request.saveAs || false
    })
    .then(downloadId => {
      sendResponse({ success: true, downloadId });
    })
    .catch(error => {
      sendResponse({ success: false, error: error.message });
    });
    return true; // 保持消息通道开启
  }
});
